/* 
 * 协议脚本 - 单设备模式
 */
import YBKC_Sanhe_5101 from '@/static/js/Agreement/YBKC_Sanhe_5101.js';
import YBKC_GUANGLU_0_300 from '@/static/js/Agreement/YBKC_GUANGLU_0-300.js';
import QFC_GUANGLU_IP65 from '@/static/js/Agreement/QFC_GUANGLU_IP65.js';
import CK_001 from '@/static/js/Agreement/CK_001.js';
import SDC_Sanhe_001 from '@/static/js/Agreement/SDC_Sanhe_001.js';
import QFB_Sanhe_001 from '@/static/js/Agreement/QFB_Sanhe_001';
import GDC_Sanhe_001 from '@/static/js/Agreement/GDC_Sanhe_001';
import BFB_GuangLu_001 from '@/static/js/Agreement/BFB_GuangLu_001_HID.js';

class AgreementManager {
    constructor() {
        this.protocolInstances = new Map();
        this.currentDevice = null; // 当前连接的设备（单设备）
        this.globalListenersInitialized = false;
        this.initGlobalListeners();
    }
    
    // 初始化全局监听
    initGlobalListeners() {
        if (this.globalListenersInitialized) return;
        
        console.log('初始化全局蓝牙监听');
        this.globalListenersInitialized = true;
    }
    
    // 获取协议实例
    getProtocolInstance(protocolName) {
        if (!this.protocolInstances.has(protocolName)) {
            const instance = this.createProtocolInstance(protocolName);
            if (instance) {
                this.protocolInstances.set(protocolName, instance);
            }
            return instance;
        }
        return this.protocolInstances.get(protocolName);
    }
    
    // 创建协议实例
    createProtocolInstance(protocolName) {
        switch (protocolName) {
            case 'YBKC_Sanhe_5101':
                return new YBKC_Sanhe_5101();
            case 'QFC_GUANGLU_IP65':
                return new QFC_GUANGLU_IP65();
            case 'CK_001':
                return new CK_001();
            case 'SDC_Sanhe_001':
                return new SDC_Sanhe_001();
            case 'QFB_Sanhe_001':
                return new QFB_Sanhe_001();
            case 'GDC_Sanhe_001':
                return new GDC_Sanhe_001();
            case 'YBKC_GUANGLU_0-300':
                return new YBKC_GUANGLU_0_300();
            case 'BFB_GuangLu_001':
                return new BFB_GuangLu_001();
            default:
                console.warn(`未知协议: ${protocolName}`);
                return null;
        }
    }
    
    // 连接设备 - 单设备模式
    async connectDevice(deviceConfig, callbacks = {}) {
        const { deviceId, protocolName } = deviceConfig;
        
        if (!deviceId || !protocolName) {
            throw new Error('设备配置缺少 deviceId 或 protocolName');
        }
        
        // 如果是同一个设备且已连接，直接返回
        if (this.currentDevice && this.currentDevice.deviceId === deviceId) {
            console.log(`设备 ${deviceId} 已连接`);
            return { deviceId, protocolName, success: true };
        }
        
        // 获取协议实例
        const protocol = this.getProtocolInstance(protocolName);
        if (!protocol) {
            throw new Error(`不支持的协议: ${protocolName}`);
        }
        
        return new Promise((resolve, reject) => {
            // 先断开当前设备（如果有）
            if (this.currentDevice) {
                console.log(`断开当前设备: ${this.currentDevice.deviceId}`);
                this.currentDevice.protocolInstance.Disconnect(this.currentDevice.deviceId);
            }
            
            protocol.Link(deviceConfig, 
                // 设备列表回调
                callbacks.onDeviceList || ((devices) => {
                    console.log('发现设备:', devices);
                }),
                // 连接成功回调
                (linkResult) => {
                    if (linkResult.status === '2500') {
                        // 设置当前设备
                        this.currentDevice = {
                            deviceId,
                            protocolName,
                            protocolInstance: protocol,
                            config: deviceConfig,
                            connected: true,
                            callbacks: callbacks
                        };
                        
                        // 设置数据回调
                        if (callbacks.onData) {
                            protocol.CallBackGetData(deviceId, (data) => {
                                if (!data.deviceId) {
                                    data.deviceId = deviceId;
                                }
                                callbacks.onData(data);
                            });
                        }
                        
                        // 设置状态回调
                        if (callbacks.onStatus) {
                            protocol.GetStatus(deviceId, callbacks.onStatus);
                        }
                        
                        console.log(`设备 ${deviceId} 连接成功`);
                        resolve({
                            deviceId,
                            protocolName,
                            success: true
                        });
                    } else {
                        reject(new Error(`连接失败: ${linkResult.message}`));
                    }
                }
            );
        });
    }
    
    // 扫描设备
    scanDevices(protocolName, onDeviceFound) {
        const protocol = this.getProtocolInstance(protocolName);
        if (!protocol) {
            throw new Error(`不支持的协议: ${protocolName}`);
        }
        
        protocol.Link(null, onDeviceFound, null);
    }
    
    // 停止扫描
    stopScan(protocolName) {
        const protocol = this.getProtocolInstance(protocolName);
        if (protocol) {
            protocol.StopFind();
        }
    }
    
    // 断开设备连接
    disconnectDevice() {
        if (this.currentDevice) {
            const { protocolInstance, deviceId } = this.currentDevice;
            protocolInstance.Disconnect(deviceId);
            this.currentDevice = null;
            console.log(`设备 ${deviceId} 已断开连接`);
        }
    }
    
    // 获取当前连接设备
    getCurrentDevice() {
        return this.currentDevice;
    }
    
    // 检查是否有设备连接
    isDeviceConnected() {
        return this.currentDevice ? this.currentDevice.connected : false;
    }
    
    // 获取当前设备ID
    getCurrentDeviceId() {
        return this.currentDevice ? this.currentDevice.deviceId : null;
    }
    
    // 设置数据回调
    setDataCallback(onData) {
        if (this.currentDevice && this.currentDevice.protocolInstance) {
            this.currentDevice.callbacks.onData = onData;
            this.currentDevice.protocolInstance.CallBackGetData(
                this.currentDevice.deviceId, 
                (data) => {
                    if (!data.deviceId) {
                        data.deviceId = this.currentDevice.deviceId;
                    }
                    onData(data);
                }
            );
        }
    }
    
    // 设置状态回调
    setStatusCallback(onStatus) {
        if (this.currentDevice && this.currentDevice.protocolInstance) {
            this.currentDevice.callbacks.onStatus = onStatus;
            this.currentDevice.protocolInstance.GetStatus(
                this.currentDevice.deviceId, 
                onStatus
            );
        }
    }
    
    // 写入数据到设备
    writeData(data) {
        if (this.currentDevice && this.currentDevice.connected) {
            this.currentDevice.protocolInstance.WriteData(
                this.currentDevice.deviceId, 
                data
            );
        }
    }
    
    // 销毁连接
    destroy() {
        if (this.currentDevice) {
            this.disconnectDevice();
        }
        this.protocolInstances.clear();
        console.log('蓝牙管理器已销毁');
    }
}

// 创建单例
const agreementManager = new AgreementManager();

export default agreementManager;